package cn.haoran.modules.palaeobios.controller;


import cn.haoran.common.utils.FastDFSUtils;
import cn.haoran.common.utils.PageUtils;
import cn.haoran.common.utils.ResultInfo;
import cn.haoran.modules.palaeobios.entity.Article;
import cn.haoran.modules.palaeobios.entity.Picture;
import cn.haoran.modules.palaeobios.service.ArticleService;
import cn.haoran.modules.palaeobios.service.PictureService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  图片前端控制器
 * </p>
 *
 * @author haoran
 * @since 2019-12-12
 */
@RestController
@RequestMapping("/picture")
public class PictureController {
    @Lazy
    private final
    ArticleService articleService;
    private final
    PictureService pictureService;
    @Autowired
    FastDFSUtils fastDFSUtils;

    @Autowired
    public PictureController(PictureService pictureService, FastDFSUtils fastDFSUtils, ArticleService articleService) {
        this.pictureService = pictureService;
        this.articleService = articleService;
    }

    @GetMapping("/list")
    @ApiOperation("分页列表")
    public ResultInfo list(@RequestParam Map<String, Object> params){
        PageUtils page = pictureService.queryPage(params);
        return ResultInfo.ok().put("page",page);
    }
    @PostMapping("save")
    @ApiOperation("保存")
    @Transactional
    /* 图片接口 */
    public ResultInfo save(@RequestParam("upFile") MultipartFile file,Article article) {
        // 方式一 上传到项目目录下
        if (file.isEmpty()) {
            return ResultInfo.ok();
        }
        // 确定保存到哪个文件夹
            String path = ClassUtils.getDefaultClassLoader().getResource("static").getPath();
            String parentPath = path+"/hrcms/images/user";
            File parent = new File(parentPath);
            if (!parent.exists()) {
                parent.mkdirs();
            }
            // 确定保存的文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            int beginIndex = originalFilename.lastIndexOf(".");
            if (beginIndex != -1) {
                suffix = originalFilename.substring(beginIndex);
            }
            String child = UUID.randomUUID().toString() + suffix;

            // 确定保存到哪个文件
            File dest = new File(parent, child);
            // 保存头像文件
            try {
                file.transferTo(dest);
            } catch (IllegalStateException | IOException e) {
                /*.println("文件上传错误:" + e.getMessage());*/
                return ResultInfo.error("文件上传未知错误");
//					throw new FileStateException(
//						"上传头像失败！所选择的文件已经不可用！");
            } // 抛出异常：FileIOException
            //					throw new FileIOException(
            //						"上传头像失败！读写数据时出现错误！");

            Picture picture = new Picture();
            picture.setArticleId(article.getId());
            picture.setUrl(child);
            pictureService.insert(picture);
            article.setTitleImgId(picture.getId());
            article.setTitleImgUrl(child);
            /*.println(article);*/
            articleService.updateById(article);

        // 方式二 上传到fastDFS 服务器
//            String url = fastDFSUtils.uploadFile(file);
//            Picture picture = new Picture();
//            picture.setArticleId(article.getId());
//            picture.setUrl(url);
//            pictureService.insert(picture);
//            article.setTitleImgId(picture.getId());
//            article.setTitleImgUrl(url);
//            /*.println(article);*/
//            articleService.updateById(article);
            return ResultInfo.ok();
        }
    @GetMapping("/info/{id}")
    @ApiOperation("根据id查询")
    public ResultInfo info(@PathVariable("id") Long id){
        Picture picture = pictureService.selectById(id);
        return ResultInfo.ok().put("picture",picture);
    }
    @PostMapping("/delete")
    @ApiOperation("批量删除或删除")
    public ResultInfo delete(@RequestBody Long[] ids){
        List<Long> list = Arrays.asList(ids);
        pictureService.deleteBatchIds(list);
        return ResultInfo.ok();
    }
    @PostMapping("/update")
    @ApiOperation("修改信息")
    public ResultInfo update(@RequestBody @Valid Picture picture){
        pictureService.updateById(picture);
        return ResultInfo.ok();
    }
}
